﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HousingInfo.Library;
using System.IO;

namespace NEWS.Admin
{
    public partial class DoccumentHouses : System.Web.UI.Page
    {
        private static string _fileImageName;
        private static TextHouseBO textBO;
        private static string modeapprove = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                modeapprove = Request.QueryString["approve"];
                if (modeapprove == "true")
                {
                    GridView1.DataSource = TextHouseBOList.GetAllTextHouseNew(false);
                    GridView1.DataBind();
                    GridView1.Columns[6].Visible = false;
                    GridView1.Columns[7].Visible = true;
                    GridView1.Columns[2].Visible = false;
                    pn_add_edit.Visible = false;
                    pn_approve.Visible = true;
                    lblxem_duyet.Text = "Duyệt Văn bản nhà đất";
                }
                else
                {
                    GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                    GridView1.DataBind();
                }
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            lbHeaderActions.Text = "Thêm Mới Văn Bản";
            messagedelete.Text = "";
            PanelActions.Visible = true;
            message.Text = "";
            lbldoccumentid.Visible = false;
            txtdoccumentid.Visible = false;
            txtdoccumentname.Text = "";
            lblink.Visible = true;
            txtlink.Text = "";
            txtlink.Visible = true;
            btndownload.Visible = false;
            btnthaydoivanban.Text = "Chọn File Văn Bản";
            btnthaydoivanban.Visible = true;
            pn_upload.Visible = false;
            lbluocxem.Visible = false;
            txtluotxem.Visible = false;
            lbluotdown.Visible = false;
            txtluotdown.Visible = false;
            lbuploaddate.Visible = false;
            txtuploaddate.Visible = false;
            btnAdd.Visible = true;
            btnUpdate.Visible = false;
            btnDelete.Visible = false;
            btnAdd.Focus();
        }

        protected void btnxoa_Click(object sender, EventArgs e)
        {
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int texthouseid = Convert.ToInt32(gvRow.Cells[3].Text);                        
                        textBO = TextHouseBO.GetTextHouseBO(texthouseid);
                        deleteExitsImage(textBO.UrlDownload);
                        TextHouseBO.DeleteTextHouseBO(texthouseid);
                    }
                    catch
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Xóa thất bại.";
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn thông tin cần xóa !!!')", true);
                return;
            }
            else
            {
                pn_result.Visible = true;
                lblthongbao.Text = "Xóa thành công !";
                GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                GridView1.DataBind();
                PanelActions.Visible = false;
            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TextHouseBO textHouseBO = TextHouseBO.GetTextHouseBO(Convert.ToInt32(GridView1.SelectedRow.Cells[3].Text));
            lbHeaderActions.Text = "Chỉnh sửa thông tin văn bản";
            lbldoccumentid.Visible = true;
            txtdoccumentid.Visible = true;
            lbluocxem.Visible = true;
            txtluotxem.Visible = true;
            lbluotdown.Visible = true;
            txtluotdown.Visible = true;
            CheckBox checkbox = (CheckBox)GridView1.SelectedRow.FindControl("cboxkichhoat");
            cbisactive.Checked = checkbox.Checked;
            btnAdd.Visible = false;
            btnUpdate.Visible = true;
            btnDelete.Visible = true;
            txtdoccumentid.Text = textHouseBO.TextHouseID.ToString();
            txtdoccumentname.Text = textHouseBO.Title;
            txtlink.Text = textHouseBO.UrlDownload;
            txtluotxem.Text = textHouseBO.ViewCount.ToString();
            txtluotdown.Text = textHouseBO.DownloadCount.ToString();
            txtuploaddate.Text = textHouseBO.CreatedDate.ToString();
            PanelActions.Visible = true;
            pn_upload.Visible = false;
            btnhuychonfile.Visible = true;
            if (txtlink.Text != "")
                btndownload.Visible = true;
            lblink.Visible = true;
            txtlink.Visible = true;
            lbuploaddate.Visible = true;
            txtuploaddate.Visible = true;
            btnthaydoivanban.Visible = true;
            btnthaydoivanban.Text = "Thay Đổi Văn Bản";
            message.Text = "";
            messagedelete.Text = "";
            btnUpdate.Focus();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    string strScript = "SelectDeSelectHeader(" + ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).ClientID + ");";
                    ((CheckBox)e.Row.Cells[0].FindControl("chkSelect")).Attributes.Add("onclick", strScript);
                }
            }
            catch
            {
                //report error
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Xem")
            {
                GridViewRow selectrow = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
                PanelActions.Visible = false;
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int doccumentid = Convert.ToInt32(txtdoccumentid.Text);
            TextHouseBO textHouses = TextHouseBO.GetTextHouseBO(doccumentid);
            textHouses.Title = txtdoccumentname.Text;
            try
            {
                if (pn_upload.Visible == true)
                {
                    message.Text = "Hoàn Thành Việc Upload File Văn Bản Cần Thay Đổi Trước";
                    btnUpdate.Focus();
                    return;
                }
                textHouses.UrlDownload = txtlink.Text;
                textHouses.IsActive = cbisactive.Checked;
                textHouses.Save();
                GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                GridView1.DataBind();
                pn_result.Visible = true;
                lblthongbao.Text = "Cập nhật thành công !";
            }
            catch
            {
                pn_result.Visible = true;
                lblthongbao.Text = "Cập nhật thất bại!";
            }
            btnUpdate.Focus();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                int docid = Convert.ToInt32(txtdoccumentid.Text);
                TextHouseBO.DeleteTextHouseBO(docid);
                deleteExitsImage(txtlink.Text);
                pn_result.Visible = true;
                lblthongbao.Text = "Đã Xoá!";
                PanelActions.Visible = false;
                GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                GridView1.DataBind();
            }
            catch
            {
                pn_result.Visible = true;
                lblthongbao.Text = "Xóa thất bại!";
                return;
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtlink.Text == "")
            {
                message.Text = "Chưa Upload File";
                btnAdd.Focus();
            }
            else
            {
                TextHouseBO textHousesAdd;
                textHousesAdd = TextHouseBO.NewTextHouseBO();
                textHousesAdd.UserName = Session["UserNameAdmin"].ToString();
                textHousesAdd.UrlDownload = txtlink.Text;
                textHousesAdd.Title = txtdoccumentname.Text;
                textHousesAdd.CreatedDate = DateTime.Now;
                textHousesAdd.ViewCount = 0;
                textHousesAdd.DownloadCount = 0;
                textHousesAdd.IsActive = cbisactive.Checked;
                try
                {
                    textHousesAdd.Save();
                    pn_result.Visible = true;
                    lblthongbao.Text = "Thêm Thành Công";
                    GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                    GridView1.DataBind();
                }
                catch
                {
                    pn_result.Visible = true;
                    lblthongbao.Text = "Thêm Thất Bại";
                    btnAdd.Focus();
                }
            }
        }

        protected void btndong_Click(object sender, EventArgs e)
        {
            PanelActions.Visible = false;
        }

        protected void btnthaydoivanban_Click(object sender, EventArgs e)
        {
            if (txtlink.Text == "" && txtdoccumentid.Visible == false)
            {
                lbchonfile.Text = "Chọn File Cần Upload";
            }
            else
            {
                lbchonfile.Text = "Chọn File Văn Bản Thay Đổi :";
            }
            pn_upload.Visible = true;
            if (btnUpdate.Visible == true)
                btnUpdate.Focus();
            else
                btnAdd.Focus();
        }

        protected void btnhuychonfile_Click(object sender, EventArgs e)
        {
            pn_upload.Visible = false;
            btnUpdate.Focus();
        }

        protected void testupload_Click(object sender, EventArgs e)
        {
            if (FileUpload_Doccument.FileName.Length > 0)
            {
                postDoccument();
                btnUpdate.Focus();
            }
            else
            {
                message.Text = "Vui Lòng Chọn File";
                btnUpdate.Focus();
            }
        }

        private void postDoccument()
        {
            try
            {
                if (FileUpload_Doccument.HasFile)
                {
                    if (FileUpload_Doccument.FileBytes.Length <= 3145728)
                    {
                        _fileImageName = FileUpload_Doccument.FileName.Replace(" ", "_");
                        
                        string formatFile = Path.GetExtension(_fileImageName);
                        //kiem tra dinh dang cho phep upload
                        if (formatFile.Equals(".doc") || formatFile.Equals(".pdf") || formatFile.Equals(".DOC") || formatFile.Equals(".PDF"))                                                                        
                        {
                            //kiem tra file da ton tai
                            string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/VanBan/" + _fileImageName);
                            if (File.Exists(filePath))
                            {
                                //neu ton tai thi doi ten
                                _fileImageName = ImageFileName(_fileImageName);
                            }
                            //thuc hien luu file
                            try
                            {
                                FileUpload_Doccument.SaveAs(Server.MapPath("~/TotalUpload/VanBan/" + _fileImageName));
                                message.Text = "Upload thành công";
                                deleteExitsImage(txtlink.Text);
                                txtlink.Text = _fileImageName;
                                btnthaydoivanban.Text = "Thay Đổi Văn Bản";
                                btndownload.Visible = true;
                                pn_upload.Visible = false;
                            }
                            catch (Exception)
                            {
                                message.Text = "Có một số vấn đề xả ra trong khi lưu. Xin hay thử lại.";
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Chỉ được upload các định dạng văn bản (.doc , .pdf)')", true);
                        }
                    }
                    else
                    {
                        message.Text = "Kích thước văn bản không quá 3MB";
                    }
                }
                else
                {
                    message.Text = "Chưa chọn file văn bản. !";
                }
            }
            catch
            {

            }
        }
        private static string ImageFileName(string fileName)
        {
            Random r = new Random();
            return r.Next(0, 10000).ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + fileName;
        }

        protected void btndownload_Click(object sender, EventArgs e)
        {
            string filePath = HttpContext.Current.Server.MapPath("~/TotalUpload/VanBan/" + txtlink.Text);
            if (File.Exists(filePath))
            {
                Response.Redirect("~/TotalUpload/VanBan/" + txtlink.Text);
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success",
                                                                "alert('Văn Bản Không Tồn Tại')", true);
                btnUpdate.Focus();
            }
        }

        private void deleteExitsImage(string filedelete)
        {
            try
            {
                var pathFileImage = Server.MapPath("~/TotalUpload/VanBan/" + filedelete);
                FileInfo fileInfo;
                if (File.Exists(pathFileImage))
                {
                    fileInfo = new FileInfo(pathFileImage);
                    fileInfo.Delete();
                }
            }
            catch
            {
            }
        }

        protected void btnapproveall_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                try
                {
                    int doccumentid = Convert.ToInt32(gvRow.Cells[3].Text);
                    textBO = TextHouseBO.GetTextHouseBO(doccumentid);
                    textBO.IsActive = true;
                    textBO.Save();
                    GridView1.DataSource = TextHouseBOList.GetAllTextHouseNew(false);
                    GridView1.DataBind();
                    pn_result.Visible = true;
                    lblthongbao.Text = "Đã duyệt tin(Tin đã được phép đăng).";
                }
                catch
                {
                    pn_result.Visible = true;
                    lblthongbao.Text = "Duyệt tin thất bại.";
                }
            } 
        }

        protected void btnapprove_Click(object sender, EventArgs e)
        {
            bool test = false;
            foreach (GridViewRow gvRow in GridView1.Rows)
            {
                CheckBox chkSel = (CheckBox)gvRow.FindControl("cbapprove");
                if (chkSel.Checked == true)
                {
                    try
                    {
                        test = true;
                        int doccumentid = Convert.ToInt32(gvRow.Cells[3].Text);
                        textBO = TextHouseBO.GetTextHouseBO(doccumentid);
                        textBO.IsActive = true;
                        textBO.Save();
                    }
                    catch
                    {
                        pn_result.Visible = true;
                        lblthongbao.Text = "Duyệt tin thất bại.";
                        return;
                    }
                }
            }
            if (test == false)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Success", "alert('Chưa chọn tin cần duyệt !!!')", true);
                return;
            }
            else
            {
                GridView1.DataSource = TextHouseBOList.GetAllTextHouseNew(false);
                GridView1.DataBind();
                pn_result.Visible = true;
                lblthongbao.Text = "Đã duyệt tin(Tin đã được phép đăng).";
            }     
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        public void BindGrid()
        {
            if (modeapprove == "true")
            {
                GridView1.DataSource = TextHouseBOList.GetAllTextHouseNew(false);
                GridView1.DataBind();
            }
            else
            {
                GridView1.DataSource = TextHouseBOList.GetTextHouseBOList();
                GridView1.DataBind();
            }
        }
    }
}
